package org.tio.sitexxx.web.server.controller.minip;

import com.alibaba.fastjson.JSON;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.http.common.HttpRequest;
import org.tio.http.server.annotation.RequestPath;
import org.tio.sitexxx.service.model.main.Charge;
import org.tio.sitexxx.service.model.main.Member;
import org.tio.sitexxx.service.model.main.Payment;
import org.tio.sitexxx.service.service.qj.ChargeService;
import org.tio.sitexxx.service.service.qj.MemberService;
import org.tio.sitexxx.service.service.qj.PaymentService;
import org.tio.sitexxx.web.server.utils.ObjectToMap;


import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestPath(value = "/charge")
public class ChargeController {
    private static Logger log = LoggerFactory.getLogger(ChargeController.class);
    /**
     * 返回charge表中充值套餐
     * @return
     */
    @RequestPath(value = "/list")
    public Map<String,List<Charge>> list(){
        Map<String,List<Charge>> value = new HashMap<>();
        List<Charge>list=ChargeService.me.getAll();
        value.put("c",list);
        return value;

    }

    /**
     * 充值订单初始化
     * @param request
     * @return
     */
    @RequestPath(value = "/pay/init")
    public Map<String,Object> pay_init(HttpRequest request){
        Map<String,Object>body= JSON.parseObject(request.getBodyString());
        Integer c_id = Integer.valueOf(body.get("c_id").toString());
        Integer amount_payable = Integer.valueOf(body.get("amount_payable").toString());
        String openid = body.get("openid").toString();

        Map<String,Object> query = new HashMap<>();
        query.put("openid",openid);
        System.out.println(openid);
        Member Member = MemberService.me.getMember(query);
        System.out.println(Member);

        //应付金额
        int pay_amount = amount_payable;
        String order_id = "c-"+System.currentTimeMillis()+ "-" + Member.getId() + "--1";
            Record payment=new Record().set("orderid",order_id).set("pay_amount",pay_amount).set("amount",pay_amount)
                    .set("type","charge").set("createdAt",new Date())
                    .set("updatedAt",new Date()).set("is_paid",0).set("memberId",Member.getId()).set("chargeId",c_id);
            Db.save("payment","id",payment);

        int payment_id=Integer.valueOf(payment.get("id").toString());
        return PayParameters.payParameters.Parameters(openid,pay_amount,order_id,payment_id,log,"charge",0);
    }

    /**
     * 用户充值成功后做相应的处理
     * @param request
     * @return
     */
    @RequestPath(value = "/pay/submit")
    public Map<String,Object> pay_submit(HttpRequest request){
        Map<String,Object>body= JSON.parseObject(request.getBodyString());
        Integer payment_id = Integer.valueOf(body.get("payment_id").toString());
        Map<String,Object> resultMap = new HashMap<>();
        Map<String,Object> query = new HashMap<>();
        query.put("id",payment_id);
        Payment Payment = PaymentService.me.getPayment(query);
        if (Payment.getId()==null) {
            resultMap.put("ok",1);
            return resultMap;
        }
        query.put("id",Payment.getMemberId());
        Member Member = MemberService.me.getMember(query);
        Charge ChargeController = ChargeService.me.getCharge(Payment.getChargeId());
//
        if(ChargeController==null){//临时
            Member.setBalance(Member.getBalance()+Payment.getPayAmount());
            resultMap.put("ok",0);
            resultMap.put("balance",Member.getBalance());
            return resultMap;
        }
        //余额为支付金额加优惠 当达不到优惠金额时 优惠为0
        if(!Payment.getIsPaid()){
            int gold = Payment.getPayAmount() + ((Payment.getPayAmount()>=ChargeController.getThreshold())?ChargeController.getReward() : 0);
            //更新余额 原子性操作
           Db.tx(()->{
               Payment.setIsPaid(true);
               PaymentService.me.update(Payment);
               Member.setBalance(Member.getBalance()!=null?Member.getBalance() + gold : gold);
               System.out.println("balance:"+Member.getBalance());
               MemberService.me.update(Member);
               return true;
           });

        }
        resultMap.put("ok",0);
        resultMap.put("balance",Member.getBalance());
        return resultMap;

    }
}